import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'

Vue.use( VueRouter )

const routes = [ {
		path: '/',
		name: 'Home',
		component: Home,
		redirect: {
			name: 'Hello'
		},
		children: [ {
				path: 'hello',
				name: 'Hello',
				component: () => import( '@/views/Hello.vue' ),
			},
			{
				path: 'article',
				name: 'Article',
				component: () => import( '@/views/post/Article.vue' )
			},
			{
				path: 'publish',
				name: 'Publish',
				component: () => import( '@/views/post/Publish.vue' )
			},
			{
				path: 'category',
				name: 'Category',
				component: () => import( '@/views/category/Category.vue' )
			}
		]
	},
	{
		path: '/login',
		name: 'Login',
		component: () => import( '@/views/Login.vue' )
	}
]

const router = new VueRouter( {
	mode: 'history',
	base: process.env.BASE_URL,
	routes
} )

// 获取 token
import {
	getToken
} from '@/utils/localStorage.js'

// 提示框
import {
	Message
} from 'element-ui'

// 前置守卫
router.beforeEach( ( to, from, next ) => {
	// 无需校验页面
	if ( to.path === '/login' ) return next()

	// 未登录
	if ( !getToken() ) return Message.warning( {
		message: '请先登录！',
		onClose: () => next( '/login' ),
		duration: 1500
	} )

	// 已登录
	next()
} )

export default router
